const path = require('node:path')

// 创建新增编辑弹窗vue文件
module.exports = (codeConfig, utils) => {
  const { hasModifyDialog, modifyApiConfig, addApiConfig } =
    codeConfig.apiConfigStates
  if (!hasModifyDialog) {
    return
  }

  const modifyDataProperties =
    modifyApiConfig?.request.schema.jsonSchema.properties
  const addDataProperties = addApiConfig?.request.schema.jsonSchema.properties
  // 以新增为主生成表单项
  const properties = addDataProperties || modifyDataProperties
  const itemsStr = []
  for (const [prop, propConfig] of Object.entries(properties)) {
    itemsStr.push(
      `useInput('${prop}', '${utils.extractText(propConfig.description)}')`
    )
  }

  const title = addApiConfig?.desc || modifyApiConfig?.desc || '标题'
  const { formItem } = require('../hooks/index.cjs')
  const code = `
    <template>
      <cs-dialog-form
        v-model:visible="store.visibleDialogModify"
        v-model="store.modifyData"
        title="${title}"
        :mode="store.isModify ? 'modify' : 'add'"
        :items="formItems"
        dialog-size="small"
        component-full-width
      />
    </template>

    <script setup lang="ts">
      /* eslint-disable @typescript-eslint/no-unused-vars */
      import { inject } from 'vue'
      import type { CsFormPropsItem } from 'csui'
      import type { Store, ModifyFormData } from '../types'
      ${formItem}

      defineOptions({ name: '${codeConfig.moduleName}Modify' })

      const store = inject<Store>('${codeConfig.moduleName}Store', {} as Store)

      const formItems: CsFormPropsItem<ModifyFormData>[] = [
        ${itemsStr.join(',')}
      ]
    </script>
  `
  utils.writeFile(
    path.join(codeConfig.modulePath, 'components', 'dialog-modify.vue'),
    code
  )
}
